package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"zy5_user/cache"
	"zy5_user/models"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	account := c.GetString("account")
	password := c.GetString("password")

	if account == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户名或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User
	user.Account = account
	user.Password = password
	if err := user.GetUserByAccount(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if user.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户已存在",
		}
		c.ServeJSON()
		return
	}

	if err := user.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "注册失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "注册成功",
	}
	c.ServeJSON()
}

func (c *UserController) Login() {
	account := c.GetString("account")
	password := c.GetString("password")

	if account == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户名或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User
	user.Account = account
	user.Password = password
	if err := user.GetUserByAccount(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if err := user.GetUserByAccount(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}

	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户不存在",
		}
		c.ServeJSON()
		return
	}

	key := "password_error_count_" + account
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()

	if user.Password != password {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Second*30)
			c.Data["json"] = map[string]interface{}{
				"code":    500,
				"message": "密码错误次数超过三次，封禁三十秒",
			}
			c.ServeJSON()
			return
		}
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "密码不正确",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "登陆成功",
	}
	c.ServeJSON()
}
